package com.example.controller;


import com.example.pojo.Supplier;
import com.example.pojo.SupplierContact;
import com.example.service.SupplierContactService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.List;


@Controller
@RequestMapping
public class SupplierContactController {
    @Autowired
    private SupplierContactService service;


    /**
     * 查询
     * @param model
     * @param cname
     * @param pid
     * @return
     */
    @GetMapping("/list")
    public String list(Model model,
                       @RequestParam(required = false) String cname,
                       @RequestParam(required = false) Integer pid){

        List<SupplierContact> list = service.allContact(cname, pid);
        List<Supplier> all = service.all();

        model.addAttribute("list", list);
        model.addAttribute("all", all);
        return "main";//转发
    }


    /**
     * 新增
     * @param supplierContact
     * @return
     */
    @PostMapping("/add")
    public String add(SupplierContact supplierContact){
        int add = service.add(supplierContact);

        if (add>0){
            return "redirect:list";//重定向
        }

        return "add";
    }

    @GetMapping("/add")
    public String add(){


        return "add";
    }


    /**
     * 删除
     * @param id
     * @return
     */
    @PostMapping("/delete")
    @ResponseBody
    public Integer delete(Integer id){
        return service.delete(id);
    }


    /**
     * 查询单条记录
     * @param model
     * @param id
     * @return
     * @throws ParseException
     */
    @GetMapping("/byId")
    public String byId(Model model,Integer id) throws ParseException {
        SupplierContact supplierContact = service.getById(id);
        model.addAttribute("supplierContact",supplierContact);
        return "update";
    }


    /**
     * 更新
     * @param supplierContact
     * @return
     */
    @PostMapping("/update")
    public String update(SupplierContact supplierContact) {
        Integer update = service.toUpdate(supplierContact);
        if (update>0){
            return "redirect:list";//重定向
        }
        return "update";
    }

}
